<template>
  <div class="index-container">
    <div class="main-header clearfix">
      <el-row>
       <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-button
            type="primary"
            icon="el-icon-plus"
            class="sureBtn"
            size="medium"
            @click="handleAdd"
          >
            新 增
          </el-button>
        </el-col>
        <el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16">
          <div class="search fr">
            <div>
              <el-input v-model="selectForm.name" size="medium" placeholder="姓名" ></el-input>
            </div>
            <div>
              <el-select v-model="selectForm.team_id" clearable placeholder="负责站点" filterable size="medium"  style="width: 100%;">
                <el-option
                  v-for="item in teamList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <el-button size="medium"    type="primary"    icon="el-icon-search" class="fr"    @click="handleSearch"> 搜索 </el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="main-content">
      <app-table
        :page-data="pageData"
        :table-columns="tableColumns"
        @current-change="handleCurrentChange"
        @handleCheckedRows="handleCheckedRows"
        @changeForMal="changeForMal"
        @cancelOrder="cancelOrder"
        @addFacelistOrder="addFacelistOrder"
      ></app-table>
    </div>
    <el-dialog
      title="服务人员"
      :visible.sync="dialogVisible"
      width="35%"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      class="dialogForm"
    >
      <div class="dialog-main">
        <el-form
          ref="ruleForm"
          :key="key"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          size="medium"
        >

          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="站点身份" prop="is_jujia">
                <el-select
                  v-model="ruleForm.is_jujia"
                  size="medium"
                  clearable
                  placeholder="请选择站点身份"
                  filterable
                  style="width: 100%;"
                >
                  <el-option :key="0" label="站点站长" :value="2"></el-option>
                  <el-option :key="1" label="站点站员" :value="1"></el-option>
                  <el-option :key="2" label="无" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="负责站点" prop="team_id">
                <el-select
                  v-model="ruleForm.team_id"
                  size="medium"
                  clearable
                  placeholder="请选择负责站点"
                  filterable
                  style="width: 100%;"
                >
                 <el-option label="无" value="0"></el-option>
                 <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="部门归属" prop="departType">
                <el-select
                  v-model="ruleForm.departType"
                  size="medium"
                  clearable
                  placeholder="请选择部门归属"
                  filterable
                  style="width: 100%;"
                  @change="handleDepartType"
                >
                  <el-option :key="0" label="行政部" :value="1"></el-option>
                  <el-option :key="1" label="业务部" :value="2"></el-option>
                  <el-option :key="2" label="运营中心" :value="3"></el-option>
                  <el-option :key="3" label="护理部" :value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="部门" prop="depart">
                <el-select
                  v-model="ruleForm.depart"
                  size="medium"
                  clearable
                  placeholder="请选择部门"
                  filterable
                  style="width: 100%;"
                  @change="handleDepart"
                >
                  <el-option v-for="(item, index) in departTypeList" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="角色" prop="role_id">
                <el-select
                  v-model="ruleForm.role_id"
                  size="medium"
                  clearable
                  placeholder="选择角色"
                  filterable
                  style="width: 100%;"
                >
                  <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" placeholder="请输入密码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="联系方式" prop="mobile">
                <el-input v-model="ruleForm.mobile" placeholder="请输入联系方式"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="性别" prop="sex">
                <el-select
                  v-model="ruleForm.sex"
                  size="medium"
                  clearable
                  placeholder="请选择性别"
                  filterable
                  style="width: 100%;"
                >
                  <el-option :key="0" label="男" :value="1"></el-option>
                  <el-option :key="1" label="女" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="ruleForm.age" placeholder="请输入年龄"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="家庭住址" prop="address">
                <el-input v-model="ruleForm.address" placeholder="请输入家庭住址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="入职时间" prop="in_time">
                <el-date-picker
                  v-model="ruleForm.in_time"
                  value-format="yyyy-MM-dd"
                  format="yyyy 年 MM 月 dd 日"
                  placeholder="选择日期时间"
                  style="width: 100%;"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="紧急联系人" prop="emergency_name">
                <el-input v-model="ruleForm.emergency_name" placeholder="请输入紧急联系人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="联系人电话" prop="emergency_mobile">
                <el-input v-model="ruleForm.emergency_mobile" placeholder="请输入紧急联系人联系方式"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="ruleForm.remark"
                  :rows="5"
                  type="textarea"
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="form-footer">
          <el-button type="primary" class="sureBtn" size="medium" @click="save">
            提 交
          </el-button>
          <el-button
            type="info"
            class="setBtn"
            size="medium"
            @click="cancel('ruleForm')"
          >
            取 消
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="负责老人"
      :visible.sync="assignVisible"
      width="50%"
      :close-on-click-modal="false"
      class="dialogForm"
    >
      <div class="dialog-main">
        <el-table
          :data="data2"
          stripe
          :header-cell-style="{ backgroundColor: '#6495ED', color: '#fff' }"
        >
          <el-table-column
            v-for="(item, index) in tableColumns2"
            :key="index"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :formatter="item.formatter"
            :filters="item.filters"
            :class-name="item.className"
            :show-overflow-tooltip="true"
          ></el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 分配老人 -->
    <el-drawer title="分配老人" size="80%" :visible.sync="dialogOlderVisible" :destroy-on-close="true" @close="dialogOlderVisible = false" :wrapperClosable="false" :with-header="false" direction="rtl">
      <user-assign-older :task="task" :teamList="teamList" @close="dialogOlderVisible = false"></user-assign-older>
    </el-drawer>

    <!-- 绑定设备 -->
    <el-drawer title="绑定设备" size="80%" :visible.sync="dialogFaceVisible" :destroy-on-close="true" @close="dialogFaceVisible = false" :wrapperClosable="false" :with-header="false" direction="rtl">
      <user-face-list :data="facedata" @cancle="dialogFaceVisible = false"></user-face-list>
    </el-drawer>

  </div>
</template>
<script>
  import appTable from "@/components/AppTable/index";
  import { servicerList, servicerAssignlist } from "@/api/oldermanager";
  import { teamList } from "@/api/wangge";
  import { getrole, unfreeze, freeze, branchsearch, rolesearch } from "@/api/depart";
  import { isPhone } from "@/utils/validate";
  import userAssignOlder from './components/user-assign-older'
  import userFaceList from './components/user-face-list'
  const validatePhone = (rule, value, callback) => {
    if (!isPhone(value)) {
      callback(new Error("请输入正确的手机号"));
    } else {
      callback();
    }
  };
  export default {
    name: "Index",
    components: { appTable, userAssignOlder, userFaceList },
    data() {
      return {
        assignVisible: false,
        dialogVisible: false,
        dialogOlderVisible: false,
        dialogFaceVisible: false,
        facedata:{},
        task: {},
        formData: {},
        data2: [],
        rules: {
          name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
          password: [{ required: true, message: "请输入密码", trigger: "blur" }],
          age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
          sex: [{ required: true, message: "请选择性别", trigger: "change" }],
          mobile: [
            { required: true, message: "请输入电话", trigger: "blur" },
            { validator: validatePhone, trigger: "blur" },
          ],
          address: [
            { required: true, message: "请输入地址", trigger: "blur" },
          ],
          emergency_name: [
            { required: true, message: "请输入紧急联系人姓名", trigger: "blur" },
          ],
           emergency_mobile: [
            { required: true, message: "请输入紧急联系联系方式", trigger: "blur" },
          ],
          is_jujia: [{ required: true, message: "选择站点身份", trigger: "change" }],
          team_id: [{ required: true, message: "选择负责站点", trigger: "change" }],
          role_id: [{ required: true, message: "选择角色", trigger: "change" }],
        },
        ruleForm: {},
        currentSelectedData: [],
        pageData: {},
        selectForm: {},
        tableColumns: [
          { prop: "name", label: "姓名" },
          { prop: "mobile", label: "联系方式" },
          { prop: "sex", label: "性别", formatter: this.genderFormatter },
          { prop: "age", label: "年龄" },
          { prop: "in_time", label: "入职时间" },
          { prop: "emergency_name", label: "紧急联系人" },
          { prop: "emergency_mobile", label: "紧急联系人电话" },
          { prop: "is_jujia", label: "站点身份", formatter: this.isJujiaFormatter},
          { prop: "team_id", label: "负责站点" , formatter: this.teamIDFormatter },
          { prop: "remark", label: "备注" },
        ],
        tableColumns2: [
          { prop: "name", label: "姓名" },
          // { prop: "mobile", label: "联系方式" },
          // { prop: "sex", label: "性别", formatter: this.genderFormatter },
          // { prop: "age", label: "年龄" },
          // { prop: "floor_str", label: "床位" },
        ],
        key: Math.random(),
        departTypeList: [],
        roleList: [],
        teamList:[]
      };
    },
    created() {},
    beforeDestroy() {},
    mounted() {
      this.getTableData();
      this.teamIndex();
    },
    methods: {
      handleDepartType(value) {
        branchsearch({type: value}).then(res => {
          this.departTypeList = res.data;
          if(res.data.length == 0) {
            this.$set(this.ruleForm, "depart", "")
            this.$set(this.ruleForm, "role_id", "")
            this.roleList = [];
          } else {
            this.$set(this.ruleForm, "depart", res.data[0].id)
            this.handleDepart(res.data[0].id)
          }
        })
      },
      handleDepart(value) {
        rolesearch({ branch_id: value}).then(res => {
          this.roleList = res.data;
          if(res.data.length == 0) {
            this.$set(this.ruleForm, "role_id", "")
          } else {
            this.$set(this.ruleForm, "role_id", res.data[0].id)
          }
        })
      },
      handleSearch() {
        this.getTableData()
      },
      genderFormatter(row, column) {
        if (row.sex == 1) {
          return "男";
        } else if (row.sex == 2) {
          return "女";
        }
      },
      isJujiaFormatter(row, column){
        if (row.is_jujia == 2) {
          return "站点站长";
        } else if (row.is_jujia == 1) {
          return "站点站员";
        } else if (row.is_jujia == 0) {
          return "无";
        }
      },
      teamIDFormatter(row, column){
        if(row['team_id'] && row.hasOwnProperty('team')){
          return row['team']['name']
        }
      },
      getTableData() {
        let data = this.selectForm;
        servicerList("get", data).then((resp) => {
          if (resp.code === 200) {
            this.pageData = resp.data;
            this.$set(this.pageData, "type", 10);
            this.$set(this.pageData, "face", true);
          }
        });
      },
      // 站点列表
      teamIndex () {
        teamList({ page_size: 100 }).then(res => {
          this.teamList = res['data']['list'];
          this.teamList.forEach((item, index, arr) => {
            item['id'] = String(item['id'])
          })
        })
      },
      save() {
        // delete this.ruleForm.password;
        this.$refs["ruleForm"].validate(async (valid) => {
          if (valid) {
            if(this.ruleForm.hasOwnProperty('in_time') && this.ruleForm['in_time']){
              this.ruleForm['in_time'] = String(this.ruleForm['in_time'])
            }
            if (this.ruleForm.id) {
              servicerList("put", Object.assign(this.ruleForm, {type: 2})).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功",
                  });
                  this.ruleForm = {};
                  this.getTableData();
                  this.cancel("ruleForm");
                }
              });
            } else {
              servicerList("post", Object.assign(this.ruleForm, {type: 2})).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "添加成功",
                  });
                  this.ruleForm = {};
                  this.getTableData();
                  this.cancel("ruleForm");
                }
              });
            }
          }
        });
      },
      cancel(formName) {
        this.$refs[formName].resetFields();
        this[formName] = {};
        this.dialogVisible = false;
      },
      handleAdd() {
        this.dialogVisible = true;
        this.key = Math.random();
        this.ruleForm = {};
      },
      handleCheckedRows(rows) {
        if (rows && rows instanceof Array && rows.length > 0) {
          this.currentSelectedData = rows;
        } else {
          this.currentSelectedData = [];
        }
      },
      handleCurrentChange(val) {
        this.selectForm.page = val;
        this.getTableData();
      },
      assignlistOrder(rows) {
        /* let params = {
          uid: rows.rows[0].id,
        };
        servicerAssignlist("get", params).then((resp) => {
          if (resp.code === 200) {
            this.data2 = resp.data;
          }
        });
        this.assignVisible = true; */
        this.task = rows.rows[0];
        this.dialogOlderVisible = true;
      },
      addFacelistOrder(rows){
        this.facedata = rows.rows[0];
        this.dialogFaceVisible = true;
      },
      cancelOrder(rows) {
        this.$confirm("确定删除该条数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let params = {
              id: rows.rows[0].id,
            };
            servicerList("delete", params).then((resp) => {
              if (resp.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getTableData();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消操作",
            });
          });
      },
      changeForMal(rows) {
        this.dialogVisible = true;
        let params = {
          id: rows.rows[0].id,
        };
        servicerList("get", params).then((resp) => {
          if (resp.code === 200) {
            resp.data['team_id'] = String(resp.data['team_id'])
            let data = resp.data;
            branchsearch({type: data.branch_type}).then(res => {
              this.departTypeList = res.data;
              rolesearch({ branch_id: data.branch_id}).then(res => {
                this.roleList = res.data;
                this.ruleForm = {...resp.data, id: rows.rows[0].id, departType: data.branch_type, depart: data.branch_id,password:''}
                // console.log(this.ruleForm)
              })
            })

          }
        });
      },
      closeDialog() {
        this.dialogVisible = false;
      },
      closeDialogForm() {
        this.dialogVisibleForm = false;
      },
      resultAvatar(data) {
        this.$set(this.ruleForm, "profile_id", data.id);
      },
    },
  };
</script>
<style lang="scss" scoped>
  .index-container {
    box-sizing: border-box;
    width: 100%;
    padding: 0 30px !important;
    margin: 0 !important;
    background: #fff !important;

    .main-header {
      padding-top: 4px;
      margin-bottom: 24px;

      .search {
        display: inline-block;

        .search-title {
          flex: 0 0 48px;
          width: 48px;
          font-size: 16px;
          line-height: 36px;
          color: #333;
        }
      }

      .search > div {
        display: inline-block;
        margin-left: 20px;
      }
    }
  }

  .form-footer {
    padding-left: 100px;
  }

  .dialog-main {
    .table-do {
      margin-bottom: 15px;
    }

    ::v-deep {
      th {
        .cell {
          color: #fff;
        }
      }
    }
  }
</style>
